<?php

namespace app\home\controller;

use app\common\controller\Home;
use app\common\library\Email;
use think\Db;

class Business extends Home
{
    // 客户模型
    protected $BusinessModel = null;

    public function __construct()
    {
        parent::__construct();

        $this->BusinessModel = model('Business.Business');
    }

    public function index()
    {
        /* 
            假设登录的用户是新用户
                头像和昵称都是空

                用模型处理 头像为空给默认 手机号隐藏中间4位 注册时间自动写入
        */
        // 获取用户信息
        // 获取cookie -> 拿主键查询数据表是否有这个用户 -> 赋值到变量

        // if ($this->request->isGet()) {
        //     $params = $this->request->param();
        //     halt($params);
        //     // $data = [
        //     //     'data' => $params['data']

        //     // ];
        //     $this->success('', '');
        // }
        return $this->fetch();
    }

    public function profile()
    {
        if ($this->request->isPost()) {
            $params = $this->request->param();

            // 封装数据
            $data = [
                'id' => $this->LoginAuth['id'],
                'nickname' => $params['nickname'],
                'email' => $params['email'],
                'gender' => $params['sex'],
            ];

            if (!empty($params['password']) && !empty($params['repass'])) {
                if ($params['password'] != $params['repass']) {
                    $this->error('密码与确认密码不一致');
                }

                // 生成新的密码盐
                $salt = build_ranstr();

                // 进行md5加密
                $password = md5($params['password'] . $salt);

                // 把密码盐以及加密好的密码追加数组
                $data['salt'] = $salt;
                $data['password'] = $password;
            }

            // 通过区的地区码获取省，市，区的地区码
            if (!empty($params['region'])) {
                $parentpath = model('Region')->where(['code' => $params['region']])->value('parentpath');

                if (!$parentpath) {
                    $this->error('选择的地区不存在');
                }

                [$province, $city, $district] = explode(',', $parentpath);

                $data['province'] = $province;
                $data['city'] = $city;
                $data['district'] = $district;
            }

            // 上传头像
            if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0) {
                $avatar = build_upload('avatar');

                if ($avatar['code'] === 0) {
                    $this->error($avatar['msg']);
                }

                $data['avatar'] = $avatar['data'];
            }

            $result = $this->BusinessModel->isUpdate(true)->save($data);

            if ($result === FALSE) {
                if (isset($data['avatar']) && $_FILES['avatar']['size'] > 0) {
                    @is_file('.' . $data['avatar']) && @unlink('.' . $data['avatar']);
                }

                $this->error('更新失败');
            } else {
                if (isset($data['avatar']) && $_FILES['avatar']['size'] > 0) {
                    @is_file('.' . $this->LoginAuth['avatar']) && @unlink('.' . $this->LoginAuth['avatar']);
                }

                $business = $this->BusinessModel->find($this->LoginAuth['id']);

                // 能到这步说明登录成功了，需要存储登录信息
                $BusData = [
                    'id' => $business['id'],
                    'nickname' => $business['nickname'],
                    'mobile' => $business['mobile'],
                    'avatar' => $business['avatar'],
                    'auth' => $business['auth']
                ];

                cookie('LoginAuth', $BusData);

                $this->success('更新成功', url('home/business/index'));
            }
        }
        return $this->fetch();
    }

    public function email()
    {
        if ($this->request->isPost()) {
            $code = $this->request->param();

            $data = [
                'code' => $code['code']
            ];

            $result = Db::name('ems')->where('code', $data['code'])->find();

            // halt($result);
            // echo $this->getLastSql();
            // model('ems')->find();

            // echo getLastSql();
            // halt($data);
            if (!$result) {
                $this->error('验证码为空或者输入有误');
            } else {
                $this->BusinessModel->isUpdate(true)->save(['auth' => 1], ['id' => $this->LoginAuth['id']]);
                // cookie("auth", 'auth', 1);
                $this->success('输入正确', url('home/business/index'));
            }
        }
        return $this->fetch();
    }

    public function send()
    {
        $email = $this->request->param('email', '', 'trim');

        $busid = $this->request->param('busid', 0, 'trim');

        $business = $this->BusinessModel->where(['id' => $busid, 'email' => $email])->find();

        if (!$business) {
            $this->error('邮箱不存在');
        }

        // 生成验证码
        $code = build_ranstr(4);

        $Ems = model('Ems')->where('email', $email)->find();

        // 开启事务
        Db::startTrans();

        if ($Ems) {
            $data = [
                'id' => $Ems['id'],
                'event' => '邮箱认证',
                'email' => $email,
                'code' => $code,
                'times' => $Ems['times'] + 1,
                'ip' => $this->request->ip()
            ];

            $result = model('Ems')->isUpdate(true)->save($data);
        } else {
            $data = [
                'event' => '邮箱认证',
                'email' => $email,
                'code' => $code,
                'times' => 1,
                'ip' => $this->request->ip()
            ];

            $result = model('Ems')->validate('common/Ems')->save($data);
        }

        if ($result === FALSE) {
            model('Ems')->rollback();
            $this->error(model('Ems')->getError());
        }

        // 实例化发送邮件类
        $Mail = new Email();

        // 邮件内容
        $content = "
            <h1>欢迎新用户！认证云课堂</h1>
            您的验证码为：<b>$code</b>
        ";

        // 发送人
        $FromEmail = config('site.mail_from');

        $SendStatus = $Mail->from($FromEmail, '云课堂')->subject('云课堂邮箱验证')->message($content)->to($email)->send();

        if ($result == true && $SendStatus == true) {
            Db::commit();
            $this->success('发送成功');
        } else {
            Db::rollback();
            $this->error($Mail->getError());
        }
    }
}
